package com.yklx.youke.admin.controller;

import com.yklx.youke.admin.service.RoleService;
import com.yklx.youke.entity.Role;
import com.yklx.youke.util.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/admin/roles")
@PreAuthorize("hasAuthority('role:read') or hasAuthority('role:write')")
public class RoleController {

    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping
    public ResponseEntity<ApiResponse<List<Role>>> getAllRoles() {
        List<Role> roles = roleService.getAllRoles();
        return ResponseEntity.ok(ApiResponse.success(roles));
    }

    @GetMapping("/{roleId}")
    public ResponseEntity<ApiResponse<Role>> getRoleById(@PathVariable String roleId) {
        Role role = roleService.getRoleById(roleId);
        if (role != null) {
            return ResponseEntity.ok(ApiResponse.success(role));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色不存在"));
        }
    }

    @PreAuthorize("hasAuthority('role:write')")
    @PostMapping
    public ResponseEntity<ApiResponse<Boolean>> createRole(@RequestBody Role role) {
        boolean success = roleService.createRole(role);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("角色创建成功", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色创建失败"));
        }
    }

    @PreAuthorize("hasAuthority('role:write')")
    @PutMapping("/{roleId}")
    public ResponseEntity<ApiResponse<Boolean>> updateRole(@PathVariable String roleId, @RequestBody Role role) {
        role.setRoleId(roleId);
        boolean success = roleService.updateRole(role);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("角色更新成功", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色更新失败"));
        }
    }

    @PreAuthorize("hasAuthority('role:write')")
    @DeleteMapping("/{roleId}")
    public ResponseEntity<ApiResponse<Boolean>> deleteRole(@PathVariable String roleId) {
        boolean success = roleService.deleteRole(roleId);
        if (success) {
            return ResponseEntity.ok(ApiResponse.success("角色删除成功", true));
        } else {
            return ResponseEntity.ok(ApiResponse.error("角色删除失败"));
        }
    }
}